package cn.com.demo.thymeleaf;

import org.junit.Test;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.templateresolver.StringTemplateResolver;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class ThymeleafDemo {
    public static void main(String[] args) throws IOException {

        // 定义、设置模板解析器
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        // 设置模板类型 # https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#what-is-thymeleaf
        // HTML、XML、TEXT、JAVASCRIPT、CSS、RAW
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setPrefix("/template/");
        templateResolver.setSuffix(".html");
        // 定义模板引擎
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        // 定义数据模型
        Context context = new Context();
        context.setVariable("username","张三");
        // 渲染模板 (输出到变量（控制台）)
        System.out.println(templateEngine.process("test", context));
        // 输出到流（文件）
        File file = new File("E:\\","test_out.html");
        Writer write = new FileWriter(file);
        templateEngine.process("test",context,write);
    }

    /**
     * 自定义字符串模板
     */
    @Test
    public void processString(){
        // 定义、设置模板解析器
        StringTemplateResolver stringTemplateResolver = new StringTemplateResolver();
        // 设置模板类型 # https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#what-is-thymeleaf
        // HTML、XML、TEXT、JAVASCRIPT、CSS、RAW
        // 字符串参考： https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#textual-template-modes
        stringTemplateResolver.setTemplateMode(TemplateMode.TEXT);
        // 定义模板引擎
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(stringTemplateResolver);
        // 定义数据模型
        Context context = new Context();
        context.setVariable("username","张三");
        // 渲染模板 (输出到变量（控制台）)
        System.out.println(templateEngine.process("[(${username})],你好", context));
    }
}
